package com.zt.questionnaire.common.interceptor;

import com.zt.questionnaire.common.ErrorCode;
import com.zt.questionnaire.common.HService;
import com.zt.questionnaire.common.msg.HErrorCode;
import com.zt.questionnaire.common.msg.HResultMsg;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

import javax.servlet.http.HttpServletRequest;

/**
 * 本类是通过spring中AOP（面向切面编程）实现登录和管理员拦截的功能
 *
 * @author sy
 */
@Aspect
@Component
public class AopInterceptor {
    private static final Logger log = LoggerFactory.getLogger(AopInterceptor.class);


    @Autowired
    private HttpServletRequest request;
    @Autowired
    HService service;


    @Pointcut("@annotation(com.zt.questionnaire.common.annotation.AccountLoginVerify)")
    public void accountLoginVerifyPointcut() {
    }


    /**
     * 用户登录验证（目前有：普通用户、养生馆技师）
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("accountLoginVerifyPointcut()")
    public Object accountLoginValidation(ProceedingJoinPoint pjp) throws Throwable {
        log.info("进入用户登录验证，sign={}", pjp.getSignature().toString());

        boolean isAccount = HService.isAccount(request);
        if (!isAccount) {
            if (pjp.getSignature().toString().startsWith("DeferredResult")) {
                DeferredResult<String> asyncResult = new DeferredResult<>();
                asyncResult.setResult(HResultMsg.createMsgError(ErrorCode.TOKEN_NOT_EXIST, "token不存在"));
                return asyncResult;
            } else {
                return HResultMsg.createMsgError(ErrorCode.TOKEN_EXPIRE, "token过期");
            }
        }

        Object result = pjp.proceed();
//        log.info("result={}", result);
        return result;

//		try {
//			Object result = pjp.proceed();
//			log.info("result={}",result);
//			return result;
//		} catch (Throwable e) {
//			log.error(e.getMessage(), e);
//			return HResultMsg.createMsgError(HErrorCode.SERVER_EXCEPTION, e.toString()+"|"+e.getMessage());
//		}

    }

    private Object proceed(ProceedingJoinPoint pjp) {
        try {
            Object result = pjp.proceed();
            log.info("result={}", result);
            return result;
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return HResultMsg.createMsgError(HErrorCode.SERVER_EXCEPTION, e.toString() + "|" + e.getMessage());
        }
    }

}
